package bknc.sgolf.servlets;

import java.io.IOException;
import java.io.PrintWriter;
 


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 



import bknc.sgolf.beans.Country;
import bknc.sgolf.beans.GolfShop;
import bknc.sgolf.services.GolfShopInformation;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

@WebServlet("/MyServlet")
public class GolfShopServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    public GolfShopServlet() {
        super();
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
 
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400");
 
        //country code coming from Android 
        String countryCode = ""; //request.getParameter("countryCode").trim();
 
        //get country information based on country code
        GolfShopInformation golfshopInformation = new GolfShopInformation();
        GolfShop golfshop = golfshopInformation.getInfo(countryCode);
 
        //if invalid country code 
        if(golfshop.getId() == null){
            JsonObject myObj = new JsonObject();
            myObj.addProperty("success", false);
            out.println(myObj.toString());
        }
 
        //if a valid country code was sent
        else {
            Gson gson = new Gson(); 
            //creates json from country object
            JsonElement sgolfObj = gson.toJsonTree(golfshop);
 
            //create a new JSON object
            JsonObject myObj = new JsonObject();
            //add property as success
            myObj.addProperty("success", true);
            //add the country object
            myObj.add("sgolfInfo", sgolfObj);
            //convert the JSON to string and send back
            out.println(myObj.toString());
        }
        out.close();
    }
}
